package io.pumelo.noti.client;

import io.netty.channel.ChannelHandlerContext;
import io.pumelo.noti.common.LOG;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class HeartBeat implements Runnable {

    private ChannelHandlerContext ctx;

    /**noti 2.0 收到心跳回复格式*/
    public static final String PING="{\"cmd\":\"ping\"}\n"; //心跳json

    @Autowired
    private NettyClient nettyClient;

    public void initChannelHandlerContext( ChannelHandlerContext ctx){
        this.ctx = ctx;
    }

    @Override
    public void run() {
        LOG.debug(this,"heartbeat");
        long lastHeartBeat = nettyClient.getLastHeartBeatTime();
        if (System.currentTimeMillis() - lastHeartBeat > 3*60*1000) {
            nettyClient.destroy();
            LOG.warn(this,"heartbeat timeout");
            nettyClient.init();
        } else {
            ctx.writeAndFlush(PING);
        }
    }

}
